"use strict";
var serialport = require('serialport');
var q = require('q');
var events_1 = require('events');
/** COM的基础类,不要直接创建 */
class BaseCom extends events_1.EventEmitter {
    constructor(portName) {
        super();
        /**
        * 用来储存超时进程的timeout object
        */
        this._timeoutId = null;
        portName = portName || "COM1";
        // 初始化时直接打开串口
        this.port = new serialport.SerialPort(portName);
        this.port.on('error', function (err) {
            console.log(err);
        });
        this.port.on('data', data => {
            if (!data || data.length === 0 || !this._defer)
                return;
            if (this._defer.promise.isFulfilled())
                return; //如果已经完成了,就不再继续后续操作了,不一定需要这句话,但是保险起见还是加上
            let buffer = (data instanceof Buffer) ? data : new Buffer(data.toString()); //要转换成buffer操作
            this._tempBuffer = Buffer.concat([this._tempBuffer, buffer], this._tempBuffer.length + buffer.length);
            if (this._dataComplete && this._dataComplete()) {
                this._timeoutId && clearTimeout(this._timeoutId); //非常重要,不要忘记在这里取消超时设置
                this._proccessData && this._proccessData(); //处理数据
            }
        });
    }
    /**
    * 设置测量超时
    * @param {number} timeout - 超时的时间,默认为5秒
    */
    _surveyTimeout(timeout) {
        timeout = timeout || 5000;
        this._timeoutId = setTimeout(() => {
            //5秒后超时,defer resolve,设置测量状态结束
            this._defer.resolve(null);
        }, timeout);
    }
    /**
    * 执行在测量前,初始化一些状态和变量
    */
    _preSurvey() {
        this._defer = q.defer(); //初始化defer,状态为未完成
        this._tempBuffer = new Buffer(0); //一开始什么数据都没,长度为0
    }
    /** 关闭串口 */
    close() {
        var defer = q.defer();
        if (this.port && this.port.isOpen()) {
            this.port.close(function () {
                defer.resolve();
            });
        } else {
            defer.resolve();
        }
        return defer.promise;
    }
    /** 打开串口 */
    open() {
        var defer = q.defer();
        if (this.port.isOpen()) {
            defer.resolve();
        } else {
            this.port.open(function () {
                defer.resolve();
            });
        }
        return defer.promise;
    }
}
exports.BaseCom = BaseCom;
